package per.com.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import per.com.bean.User;
import per.com.common.Const;
import per.com.common.ServerResponse;
import per.com.utils.GsonUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * @author zxy
 */
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Const.CURRENT_USER);
        if (user == null || user.getStatus().intValue() != Const.Role.ROLE_ADMIN){
            //重置response
            response.reset();
            //设置编码格式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter pw = response.getWriter();
            if (user == null){
                pw.write(GsonUtils.objectToGson(ServerResponse.createByErrorMessage("用户未登录，被拦截器拦截，请先登录")));
            }else {
                pw.write(GsonUtils.objectToGson(ServerResponse.createByErrorMessage("不是管理员，被拦截器拦截，没有权限进行操作")));
            }

            pw.flush();
            pw.close();
            return false ;
        }else {
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
